package subscriber

import (
	"fmt"
	"os"
	"os/signal"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

const (
	serverURI    = "tcp://mq.heatwatch.cn:1983"   // MQTT 服务器地址
	topic        = "tmr/ryjt/kptmqtt1/ryjt1/pycx" // 主题名称
	qos          = 1                              // QoS 等级
	clientID     = "ryjt1"                        // 客户端 ID
	cleanSession = true                           // 清除会话状态
	password     = "123"                          // 密码
	userName     = "kptmqtt1"                     // 用户名
)

func NewSubscriber() {
	// 创建 MQTT 客户端连接选项
	opts := MQTT.NewClientOptions().
		AddBroker(serverURI).
		SetClientID(clientID).
		SetCleanSession(cleanSession).
		SetPassword(password).
		SetUsername(userName)

	// 创建 MQTT 客户端
	client := MQTT.NewClient(opts)

	// 连接到 MQTT 服务器
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	fmt.Println("Connected to MQTT broker:", serverURI)

	// 订阅主题
	if token := client.Subscribe(topic, qos, messageHandler); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	fmt.Println("Subscribed to topic:", topic)

	// 捕获中断信号以优雅地关闭连接
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	<-c

	// 取消订阅并断开连接
	client.Unsubscribe(topic)
	client.Disconnect(250)
	fmt.Println("Disconnected from MQTT broker")
}

// 消息处理函数，当接收到新消息时调用
func messageHandler(client MQTT.Client, msg MQTT.Message) {
	fmt.Printf("Received message on topic: %s\n", msg.Topic())
	fmt.Printf("Message: %s\n", msg.Payload())
}
